//
//  ZXY_AddCaseVC.m
//  LawProjection
//
//  Created by 宇周 on 14/11/12.
//  Copyright (c) 2014年 duostec. All rights reserved.
//

#import "ZXY_AddCaseVC.h"
#import "ZXY_MyCaseChooseCell.h"
#import "ZXY_MyCaseFeeCell.h"
#import "ZXY_MyCaseChooseCityCell.h"
#import "ZXY_MyCaseChooseRoleCell.h"
#import "ZXY_MyCaseFileAttrCell.h"
#import "ZXY_MyCaseMoneyCell.h"
#import "ZXY_MyCaseBtnCell.h"
#import <MBProgressHUD/MBProgressHUD.h>
#import "LawCaseTypeEntity.h"
#import "LawEntityHelper.h"
#import "LawCityEntity.h"
#import "ZXY_CityZoneVC.h"
#import "ELCImagePickerHeader.h"
#import "ZXY_WebVC.h"
#import "ZXY_SearchLawerVC.h"
#import "LCYLawyerDetailViewController.h"
@interface ZXY_AddCaseVC ()<UITableViewDataSource,UITableViewDelegate,UIPickerViewDataSource,UIPickerViewDelegate,UITextFieldDelegate,ZXY_ChooseCityDelegate,ELCImagePickerControllerDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,UIAlertViewDelegate,UIActionSheetDelegate>
{
    __weak IBOutlet UIButton *submitBtn;
    NSMutableArray *allFileArr;
    __weak IBOutlet UITableView *currentTable;
    NSMutableArray *allLawerArr;
    //NSMutableArray *allCaseType;
    //NSArray        *professionArr;
    UITextField    *moneyText;
    NSString       *moneyString;
    UIToolbar *topBar;
    NSDictionary *currentCase;
    LawCityEntity *_provinceEntity;
    LawCityEntity *_cityEntity;
    IBOutlet UIView *pickView;
    __weak IBOutlet UIPickerView *pickVC;
    NSString *_currentRole;
    UIActionSheet  *picherSheet;
    NSDictionary   *currentSelectAttr;
    NSString       *agencyCost;
    NSString       *total;
    NSString       *discounted;
    NSString       *_caseID;
    NSDictionary   *_currentCaseInfo;
    NSString       *_status;
    NSString       *_stage;
    BOOL           isFinish;
}
- (IBAction)submitAction:(id)sender;
@property (nonatomic,strong)NSArray *professionArr;
@end

@implementation ZXY_AddCaseVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self registLawersNoti];
    _currentRole = @"1";
    // Do any additional setup after loading the view.
    [self initNavi];
    if(_caseID)
    {
        [self startInitDetail];
    }
    [self loadCaseTypeData];
    topBar = [self toolBarWithRight:@"完成" andLeft:nil withRightBtnSel:@selector(hideKeyBoard) andLeftBtnSel:nil];
    if(allFileArr == nil)
    {
        allFileArr = [[NSMutableArray alloc] init];
    }
    [self initData];
}



- (void)startFromCaseID:(NSString *)caseID
{
    
    _caseID = caseID;
}

- (void)startInitDetail
{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSString *urlString = [NSString stringWithFormat:@"%@%@",API_HOST_URL,API_CASEDETAIL_URL];
    NSDictionary *parameter = @{
                                @"id":_caseID
                               };
    [self startLoadDataGETCSRF:urlString withPatameter:parameter successBlock:^(NSData *responseData) {
        NSDictionary *returnDic = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:nil];
        if(![returnDic.allKeys containsObject:@"data"])
        {
            if([returnDic.allKeys containsObject:@"error"])
            {
                [self showAlertWarnningView:@"提示" andContent:returnDic[@"error"][@"message"]];
            }
            else
            {
                [[UserInfoDetail sharedInstance] userLogOut];
                [self performSelector:@selector(toLoginVC) withObject:nil afterDelay:1];
                
            }
        }
        else
        {
            _currentCaseInfo   = returnDic[@"data"];
           // NSNumber *statusNum =
            _status            = _currentCaseInfo[@"status"];
            _stage             = _currentCaseInfo[@"stage"];
            if([_status isEqualToString:@"0"]&&[_stage isEqualToString:@"0"])
            {
                isFinish = NO;
            }
            else
            {
                isFinish = YES;
            }
            
            NSNumber *costNum  = _currentCaseInfo[@"costs"];
            agencyCost         = costNum.stringValue;
            NSNumber *totalNum = _currentCaseInfo[@"adviceFee"];
            total = totalNum.stringValue;
            NSNumber *disNum   = _currentCaseInfo[@"discount"];
            discounted = disNum.stringValue;
            NSNumber *roleNum = _currentCaseInfo[@"role"];
            _currentRole     = roleNum.stringValue;
            NSNumber *moneyNum = _currentCaseInfo[@"amount"];
            moneyString      = moneyNum.stringValue;
            NSString *typeString = _currentCaseInfo[@"type"];
            currentCase      = _currentCaseInfo[@"options"][@"category"][typeString];
            if(allFileArr == nil)
            {
                allFileArr = [[NSMutableArray alloc] init];
            }
            NSArray *files = _currentCaseInfo[@"files"];
            for(NSDictionary *fileInfo in files)
            {
                NSString *fileName = [fileInfo objectForKey:@"fileName"];
                NSString *fileId   = [fileInfo objectForKey:@"fileId"];
                NSMutableDictionary *fileDic = [NSMutableDictionary dictionaryWithObjectsAndKeys:fileName,@"name",fileId,@"fileId",@"YES",@"isUpload", nil];
                [allFileArr addObject:fileDic];
                
            }
            NSArray *lawyers = _currentCaseInfo[@"intention"];
            if(allLawerArr == nil)
            {
                allLawerArr = [[NSMutableArray alloc] init];
            }
            for(NSString *lawyerInfo in lawyers)
            {
                NSDictionary *userDic = _currentCaseInfo[@"options"][@"user"];
                NSDictionary *currentLawyer = userDic[lawyerInfo];
                [allLawerArr addObject:currentLawyer];
            }
            [currentTable reloadData];
        }
    } errorBlock:^(NSError *error) {
        [[UserInfoDetail sharedInstance] userLogOut];
        [self performSelector:@selector(toLoginVC) withObject:nil afterDelay:1];;
    }];

}

- (void)toLoginVC
{
    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    [self performSegueWithIdentifier:@"toLoginVC" sender:self];
}


- (void)initData
{
    agencyCost = @"";
    total      = @"";
    discounted = @"";
}

- (void)initNavi
{
    [self setLeftNaviItem:@"back_arrow"];
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName, nil]];
    [self setNaviTitle:@"案件委托" withPositon:1 ];
    [self setRightNaviItem:@"home_phone"];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
}

- (void)loadCaseTypeData
{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSString *urlString = [NSString stringWithFormat:@"%@%@",API_HOST_URL,API_CATEGORY_URL];
    NSDictionary *parameter = @{
                                @"type":@"CaseType"
                                };
    [self startLoadDataGETCSRF:urlString withPatameter:parameter successBlock:^(NSData *responseData) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:nil];
        NSDictionary *jsonDatas = [jsonDic objectForKey:@"data"];
        NSArray      *items     = [jsonDatas objectForKey:@"items"];
        [self initData:items];
    } errorBlock:^(NSError *error) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        [self showAlertWarnningView:@"提示" andContent:@"数据获取错误，请重新登录"];
    }];
}

- (void)initData:(NSArray *)currentProfess
{
    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
   
    self.professionArr   = [[NSArray alloc] initWithArray:currentProfess];
    if(currentCase == nil)
    {
        currentCase = [self.professionArr objectAtIndex:0];
    }
    [currentTable reloadData];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(section == 0)
    {
        return 4;
    }
    else if (section == 1)
    {
        if(isFinish)
        {
            return allFileArr.count;
        }
        return allFileArr.count +1;
    }
    else if (section == 2)
    {
        if(isFinish)
        {
            return allLawerArr.count;
        }
        return allLawerArr.count +1;
    }
    else
    {
        return 1;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger currentRow     = indexPath.row;
    NSInteger currentSection = indexPath.section;
    if(currentSection == 0)
    {
        return 52;
    }
    else if (currentSection == 1)
    {
        if(currentRow == allFileArr.count )
        {
            return 50;
        }
        else
        {
            return 38;
        }
    }
    else if(currentSection == 2)
    {
        if(currentRow == allLawerArr.count )
        {
            return 50;
        }
        else
        {
            return 38;
        }

    }
    else
    {
        return 118;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger currentRow = indexPath.row;
    NSInteger currentSection = indexPath.section;
    if(currentSection == 0)
    {
        if(currentRow == 0)
        {
            ZXY_MyCaseChooseCell *chooseCell = [tableView dequeueReusableCellWithIdentifier:MyCaseChooseCellID];
            if(currentCase)
            {
                chooseCell.valueLbl.text = [currentCase objectForKey:@"name"];
            }
            return chooseCell;
        }
        else if (currentRow == 1)
        {
            ZXY_MyCaseChooseRoleCell *roleCell = [tableView dequeueReusableCellWithIdentifier:MyCaseChooseRoleCellID];
            if([_currentRole isEqualToString:@"1"])
            {
                [roleCell.roleSeg setSelectedSegmentIndex:0];
            }
            else
            {
                [roleCell.roleSeg setSelectedSegmentIndex:1];
            }
            roleCell.currentRole = ^(NSString *roleID)
            {
                _currentRole = roleID;
            };
            return roleCell;
        }
        else if (currentRow == 2)
        {
            ZXY_MyCaseMoneyCell *moneyCell = [tableView dequeueReusableCellWithIdentifier:MyCaseMoneyCellID];
            moneyText = moneyCell.valueLbl;
            if(moneyString)
            {
                moneyText.text = moneyString;
            }
            moneyText.delegate = self;
            moneyText.returnKeyType = UIReturnKeyDone;
            [moneyText addTarget:self action:@selector(hideKeyBoard) forControlEvents:UIControlEventEditingDidEndOnExit];
            [moneyText setInputAccessoryView:topBar];
            return moneyCell;
        }
        else
        {
            ZXY_MyCaseChooseCityCell *cityCell = [tableView dequeueReusableCellWithIdentifier:MyCaseChooseCityCellID];
            if(_provinceEntity)
            {
                NSString *locationString = [NSString stringWithFormat:@"%@ %@",_provinceEntity.name,_cityEntity.name];
                cityCell.valueLbl.text = locationString;
            }
            return cityCell;
        }
    }
    else if (currentSection == 1)
    {
        if(currentRow == allFileArr.count)
        {
            ZXY_MyCaseBtnCell *cell = [tableView dequeueReusableCellWithIdentifier:MyCaseBtnCellID];
            cell.titleLbl.text = @"上传文件";
            return cell;
        }
        else
        {
            ZXY_MyCaseFileAttrCell *cell = [tableView dequeueReusableCellWithIdentifier:MyCaseFileAttrCellID];
            //return fileCell;
            NSDictionary *imageInfo = [allFileArr objectAtIndex:currentRow];
            //cell.indexLbl.text         = [NSString stringWithFormat:@"%d",indexPath.row+1];
            cell.titleLbl.text          = [imageInfo objectForKey:@"name"];
            if([imageInfo[@"isUpload"] isEqualToString:@"NO"])
            {
                cell.stateLbl.text = @"等待";
            }
            else if ([imageInfo[@"isUpload"] isEqualToString:@"YES"])
            {
                cell.stateLbl.text = @"操作";
            }
            else
            {
                cell.stateLbl.text = @"上传中";
            }
            return cell;
        }
    }
    else if(currentSection == 2)
    {
        if(currentRow == allLawerArr.count)
        {
            ZXY_MyCaseBtnCell *cell = [tableView dequeueReusableCellWithIdentifier:MyCaseBtnCellID];
            cell.titleLbl.text = @"选择律师";
            return cell;
        }
        else
        {
            ZXY_MyCaseFileAttrCell *fileCell = [tableView dequeueReusableCellWithIdentifier:MyCaseFileAttrCellID];
            NSDictionary *currentDic = [allLawerArr objectAtIndex:indexPath.row];
            fileCell.titleLbl.text      = [currentDic objectForKey:@"name"];
            fileCell.stateLbl.text      = @"";
            return fileCell;
        }

    }
    else
    {
        ZXY_MyCaseFeeCell *cell = [tableView dequeueReusableCellWithIdentifier:MyCaseFeeCellID];
        cell.agencyCostLbl.text = agencyCost;
        cell.totalLbl.text      = total;
        cell.discountedLbl.text = discounted;
        if(agencyCost.length>0)
        {
            [cell.tipsLbl setHidden:NO];
        }
        else
        {
            [cell.tipsLbl setHidden:YES];
        }
        return cell;
    }
}


- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if(section == 0)
    {
        return @"";
    }
    else if (section == 1)
    {
        return @"相关文件";
    }
    else if(section == 2)
    {
        return @"意向律师";
    }
    else
    {
        return @"";
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if(section == 0)
    {
        return 15;
    }
    else if (section == 1)
    {
        return 25;
    }
    else if(section == 2)
    {
        return 25;
    }
    else
    {
        return 15;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger currentRow     = indexPath.row;
    NSInteger currentSection = indexPath.section;
    if(currentSection == 0&& currentRow == 0)
    {
        if(isFinish)
        {
            return;
        }
        [self showPickAction:nil];
    }
    if(currentSection == 0&& currentRow == 3)
    {
        if(isFinish)
        {
            return;
        }
        UIStoryboard *story = [UIStoryboard storyboardWithName:@"UserLoginRegist" bundle:nil];
        ZXY_CityZoneVC *cityZone = [story instantiateViewControllerWithIdentifier:@"cityVC"];
        [cityZone setLevel:YES];
        cityZone.delegate = self;
        [self.navigationController pushViewController:cityZone animated:YES];
    }
    if(currentSection == 1&&currentRow == allFileArr.count)
    {
        if(isFinish)
        {
            return;
        }
        [self chooseImage];
    }
    
    if(currentSection == 1 &&currentRow <allFileArr.count)
    {
        NSDictionary *currentDic = [allFileArr objectAtIndex:currentRow];
        if([currentDic[@"isUpload"] isEqualToString:@"YES"])
        {
            currentSelectAttr = currentDic;
            if(!isFinish)
            {
                UIActionSheet *sheet     = [[UIActionSheet alloc] initWithTitle:@"您要" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"查看附件",@"删除附件", nil];
                sheet.tag = 5000;
                [sheet showInView:self.view];
            }
            else
            {
                UIActionSheet *sheet     = [[UIActionSheet alloc] initWithTitle:@"您要" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"查看附件", nil];
                sheet.tag = 5001;
                [sheet showInView:self.view];
            }
            
        }
        
    }
    
    if(currentSection == 2&& currentRow == allLawerArr.count)
    {
        [self selectLawyers];
    }
    if(currentSection == 2&& currentRow < allLawerArr.count)
    {
        NSDictionary *currentDic = [allLawerArr objectAtIndex:currentRow];
        NSString *currentID = currentDic[@"_id"];
        UIStoryboard *icyStoryboard = [UIStoryboard storyboardWithName:@"LCYLawyerDetail" bundle:nil];
        LCYLawyerDetailViewController *lawyerDetailVC = [icyStoryboard instantiateInitialViewController];
        lawyerDetailVC.lawyerID = currentID;
        [self.navigationController pushViewController:lawyerDetailVC animated:YES];
    }

}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 2)
    {
        if(allLawerArr.count == 0)
        {
            return NO;
        }
        if(allLawerArr.count>indexPath.row)
        {
            return YES;
        }
        return NO;
    }
    return NO;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 2)
    {
        if(allLawerArr.count>indexPath.row)
        {
           if(editingStyle == UITableViewCellEditingStyleDelete)
           {
               NSDictionary *deleteRow = [allLawerArr objectAtIndex:indexPath.row];
               [allLawerArr removeObject:deleteRow];
               [currentTable reloadData];
           }
        }
    }

}

// !!!:选择器相关
- (void)showPickAction:(id)sender
{
    if(isFinish)
    {
        return;
    }
    [self hideKeyBoard];
    CGSize pickerProfessionS = pickView.frame.size;
    if(![self.view.subviews containsObject:pickView])
    {
        pickView.frame = CGRectMake(0, self.view.frame.size.height, pickerProfessionS.width, pickerProfessionS.height);
        [self.view addSubview:pickView];
    }
    else
    {
        return;
    }
    [UIView animateWithDuration:0.3 animations:^{
        pickView.frame = CGRectMake(0, self.view.frame.size.height-pickerProfessionS.height, pickerProfessionS.width, pickerProfessionS.height);
    }];

}

- (IBAction)hidePickAction:(id)sender {
    CGSize pickerProfessionS = pickView.frame.size;
    [UIView animateWithDuration:0.3 animations:^{
        pickView.frame = CGRectMake(0, self.view.frame.size.height, pickerProfessionS.width, pickerProfessionS.height);
    }completion:^(BOOL finished) {
        [pickView removeFromSuperview];
    }];
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return self.professionArr.count;
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    NSDictionary *entity = [self.professionArr objectAtIndex:row];
    return [entity objectForKey:@"name"];
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    NSDictionary *entity = [self.professionArr objectAtIndex:row];
    currentCase = entity;
    [currentTable reloadData];
    [self countCaseMoney];
}

// !!!:选择器相关结束


// !!!:计算起诉金额
- (void)countCaseMoney
{
    if([self checkForCaseMoney])
    {
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        NSString *urlString = [NSString stringWithFormat:@"%@%@",API_HOST_URL,API_CASEMONEY_URL];
        NSDictionary *parameter = @{
                                    @"uid":[[UserInfoDetail sharedInstance] getUserID],
                                    @"caseType":currentCase[@"categoryId"],
                                    @"area":_provinceEntity.name,
                                    @"amount":moneyString
                                    };
        [self startLoadDataPOSTCSRF:urlString withPatameter:parameter successBlock:^(NSData *responseData) {
            NSDictionary *responseDic = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:nil];
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
            if([responseDic.allKeys containsObject:@"error"])
            {
                NSDictionary *errorDic = [responseDic objectForKey:@"error"];
                NSString     *errorString = [errorDic objectForKey:@"message"];
                [self showAlertWarnningView:@"提示" andContent:errorString];
            }
            else
            {
                discounted = responseDic[@"data"][@"legalCost"][@"discounted"];
                agencyCost = responseDic[@"data"][@"agencyCost"];
                total      = responseDic[@"data"][@"legalCost"][@"total"];
                [currentTable reloadData];
            }
        } errorBlock:^(NSError *error) {
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];;
        }];
    }
    else
    {
        agencyCost = @"";
        total      = @"";
        discounted = @"";
    }
    
}

- (BOOL)checkForCaseMoney
{
     if(currentCase == nil)
     {
         return NO;
     }
     if(![self isUserInputNum:moneyString]||moneyString==nil)
     {
         return NO;
     }
     if(_provinceEntity == nil)
     {
         return NO;
     }
    return YES;
}

// !!!:选择律师

- (void)selectLawyers
{
    UIStoryboard *story = [UIStoryboard storyboardWithName:@"tabLawPageStory" bundle:nil];
    ZXY_SearchLawerVC *searchLaw = [story instantiateViewControllerWithIdentifier:@"searchLawerID"];
    [searchLaw setIsChoose:YES];
    [self.navigationController pushViewController:searchLaw animated:YES];
}

- (void)notiMethod:(NSNotification *)notiArr
{
    allLawerArr = [NSMutableArray arrayWithArray:[notiArr object]];
    [currentTable reloadData];
    NSLog(@"%d",self.professionArr.count);
}

- (void)registLawersNoti
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notiMethod:) name:@"lawyersNoti" object:nil];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"lawyersNoti" object:nil];
}

// !!!:选择律师结束
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [UIView animateWithDuration:0.3 animations:^{
        self.view.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y-40, self.view.frame.size.width, self.view.frame.size.height);
    }];
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [UIView animateWithDuration:0.3 animations:^{
        self.view.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y+40, self.view.frame.size.width, self.view.frame.size.height);
    }];
    if(textField == moneyText)
    {
        moneyString = moneyText.text;
        [self countCaseMoney];
    }
}

- (void)hideKeyBoard
{
    [moneyText resignFirstResponder];
}

- (void)userChooseCityDelegate:(LawCityEntity *)provinceEntity andCityEntity:(LawCityEntity *)cityEntity withZoneEntity:(LawCityEntity *)zoneEntity
{
    _provinceEntity = provinceEntity;
    _cityEntity     = cityEntity;
    [currentTable reloadData];
    [self countCaseMoney];
}

// !!!:上传文件
- (void)chooseImage
{
    if(allFileArr.count>=10)
    {
        [self showAlertWarnningView:@"" andContent:@"最多只能选择十张照片"];
        return;
    }
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        
        picherSheet = [[UIActionSheet alloc] initWithTitle:@"请选择方式" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"图库选取",@"拍照选取", nil];
    }
    else
    {
        
        picherSheet = [[UIActionSheet alloc] initWithTitle:@"请选择方式" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"图库选取", nil];
    }
    [picherSheet showInView:self.view];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(actionSheet.tag == 5000)
    {
        if(buttonIndex == 0)
        {
            NSString     *fileID     = [currentSelectAttr objectForKey:@"fileId"];
            NSString     *fileName   = [currentSelectAttr objectForKey:@"name"];
            NSString     *stringURL  = [NSString stringWithFormat:@"%@%@?fileId=%@",API_HOST_URL,API_DOWNLOAD_URL,fileID];
            ZXY_WebVC    *webVC      = [[ZXY_WebVC alloc] init];
            webVC.title = fileName;
            [webVC setDownLoadURL:stringURL];
            [self.navigationController pushViewController:webVC animated:YES];
        }
        else if (buttonIndex == 1)
        {
            [allFileArr removeObject:currentSelectAttr];
            [currentTable reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationNone];
        }
        
    }
    else if (actionSheet.tag == 5001)
    {
        if(buttonIndex == 0)
        {
            NSString     *fileID     = [currentSelectAttr objectForKey:@"fileId"];
            NSString     *fileName   = [currentSelectAttr objectForKey:@"name"];
            NSString     *stringURL  = [NSString stringWithFormat:@"%@%@?fileId=%@",API_HOST_URL,API_DOWNLOAD_URL,fileID];
            ZXY_WebVC    *webVC      = [[ZXY_WebVC alloc] init];
            webVC.title = fileName;
            [webVC setDownLoadURL:stringURL];
            [self.navigationController pushViewController:webVC animated:YES];
        }
        
    }
    else if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        
        
        if(buttonIndex == 0)
        {
            ELCImagePickerController *pickerController = [[ELCImagePickerController alloc] initImagePicker];
            [pickerController setMaximumImagesCount:10-allFileArr.count];
            pickerController.returnsOriginalImage = NO;
            pickerController.returnsImage = YES;
            pickerController.onOrder = YES;
            pickerController.imagePickerDelegate = self;
            [self presentViewController:pickerController animated:YES completion:^{
                
            }];
        }
        else if (buttonIndex == 1)
        {
            UIImagePickerController *pickerImage = [[UIImagePickerController alloc] init];
            pickerImage.sourceType = UIImagePickerControllerSourceTypeCamera;
            pickerImage.allowsEditing = NO;
            pickerImage.delegate = self;
            [self presentViewController:pickerImage animated:YES completion:^{
                
            }];
            
        }
    }
    else
    {
        ELCImagePickerController *pickerController = [[ELCImagePickerController alloc] initImagePicker];
        [pickerController setMaximumImagesCount:10-allFileArr.count];
        pickerController.returnsOriginalImage = NO;
        pickerController.returnsImage = YES;
        pickerController.onOrder = YES;
        pickerController.imagePickerDelegate = self;
        [self presentViewController:pickerController animated:YES completion:^{
            
        }];
    }
}


- (void)elcImagePickerController:(ELCImagePickerController *)picker didFinishPickingMediaWithInfo:(NSArray *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
    if(allFileArr.count+info.count>10)
    {
        [self showAlertWarnningView:@"" andContent:@"最多只能选择十张图片"];
        return;
    }
    for(NSDictionary *dict in info)
    {
        if ([dict objectForKey:UIImagePickerControllerMediaType] == ALAssetTypePhoto){
            if ([dict objectForKey:UIImagePickerControllerOriginalImage]){
                UIImage* image      = [dict objectForKey:UIImagePickerControllerOriginalImage];
                NSString *imageName = [self stringForImageName];
                NSMutableDictionary *imageInfo = [NSMutableDictionary dictionaryWithObjectsAndKeys:imageName,@"name",image,@"data",@"NO",@"isUpload", nil];
                [allFileArr addObject:imageInfo];
            }
        }
    }
    [self performSelectorInBackground:@selector(uploadImage) withObject:nil];
}

- (NSString *)stringForImageName
{
    NSDateFormatter *dateFormtter = [[NSDateFormatter alloc] init];
    [dateFormtter setDateFormat:@"yyyyMMddHHmmssSSS"];
    NSString *currentDateString = [dateFormtter stringFromDate:[NSDate date]];
    int valueOne   = arc4random_uniform(10);
    int valueTwo   = arc4random_uniform(10);
    int valueThree = arc4random_uniform(10);
    NSString *returnString = [NSString stringWithFormat:@"%@%d%d%d.jpg",currentDateString,valueOne,valueTwo,valueThree];
    return returnString;
}


- (void)elcImagePickerControllerDidCancel:(ELCImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
    
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
    if(allFileArr.count+1>10)
    {
        [self showAlertWarnningView:@"" andContent:@"最多只能选择十张图片"];
        return;
    }
    
    NSString *imageName = [self stringForImageName];
    NSMutableDictionary *imageInfo = [NSMutableDictionary dictionaryWithObjectsAndKeys:imageName,@"name",image,@"data",@"NO",@"isUpload", nil];
    [allFileArr addObject:imageInfo];
    
    [self performSelectorInBackground:@selector(uploadImage) withObject:nil];
    //[currentTable reloadData];
}

- (BOOL)isUpOver
{
    BOOL over = YES;
    for(NSMutableDictionary *imageInfo in allFileArr)
    {
        if([[imageInfo objectForKey:@"isUpload"] isEqualToString:@"NO"])
        {
            over = NO;
        }
    }
    return YES;
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (void)uploadImage
{
    __block BOOL canContinue = YES;
    __block BOOL canDown = YES;
    __block int  currentIndex=0;
    while (canContinue) {
        if(canDown)
        {
            
            NSMutableDictionary *fileInfo = [allFileArr objectAtIndex:currentIndex];
            if([fileInfo[@"isUpload"] isEqualToString:@"NO"])
            {
                canDown = NO;
                UIImage *image = [fileInfo objectForKey:@"data"];
                NSString *fileString = [fileInfo objectForKey:@"name"];
                [fileInfo setObject:@"current" forKey:@"isUpload"];
                dispatch_sync(dispatch_get_main_queue(), ^{
                    [currentTable reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationNone];
                });
                
                NSData *imageData = UIImageJPEGRepresentation(image, 0.8);
                [self startUploadFileData:imageData withFileName:fileString andProgress:nil completeSuccess:^(NSDictionary *responseData) {
                    NSArray *dataDic = [responseData objectForKey:@"data"];
                    NSString     *fileId  = [[dataDic objectAtIndex:0] objectForKey:@"_id"];
                    [fileInfo setObject:fileId forKey:@"fileId"];
                    [fileInfo setObject:@"YES" forKey:@"isUpload"];
                    [currentTable reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationNone];
                    currentIndex ++;
                    if(currentIndex >= allFileArr.count)
                    {
                        canContinue = NO;
                        //                        dispatch_sync(dispatch_get_main_queue(), ^{
                        //                            [currentTable reloadData];
                        //                        });
                    }
                    else
                    {
                        canDown = YES;
                    }
                    
                } completeError:^(NSError *error) {
                    currentIndex++;
                    [fileInfo setObject:@"NO" forKey:@"isUpload"];
                    if(currentIndex >= allFileArr.count)
                    {
                        canContinue = NO;
                        //                        dispatch_sync(dispatch_get_main_queue(), ^{
                        //                            [currentTable reloadData];
                        //                        });
                    }
                    else
                    {
                        canDown = YES;
                    }
                    
                }];
            }
            else
            {
                currentIndex ++;
                if(currentIndex >= allFileArr.count)
                {
                    canContinue = NO;
                    //                    dispatch_sync(dispatch_get_main_queue(), ^{
                    //                        [currentTable reloadData];
                    //                    });
                }
                else
                {
                    canDown = YES;
                }
                
            }
            
        }
        
    }
    NSLog(@"结束了");
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

// !!!:提交相关

- (IBAction)submitAction:(id)sender
{
    if([self isUserInputValidate])
    {
        UIAlertView *sAlert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您确定提交案件委托吗？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"提交", nil];
        sAlert.tag = 5000;
        [sAlert show];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(buttonIndex == 1)
    {
        NSString *urlString = [NSString stringWithFormat:@"%@%@",API_HOST_URL,API_CASEADD_URL];
        NSDictionary *urlParameter = [self toSubmitParameter];
        [self startLoadDataPOSTCSRF:urlString withPatameter:urlParameter successBlock:^(NSData *responseData) {
            NSDictionary *responseDic = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:nil];
            if([responseDic.allKeys containsObject:@"error"])
            {
                [self showAlertWarnningView:@"提示" andContent:responseDic[@"error"][@"message"]];
            }
            else
            {
                [self.navigationController popViewControllerAnimated:YES];
            }
        } errorBlock:^(NSError *error) {
            ;
        }];

    }
}

- (NSDictionary *)toSubmitParameter
{
    NSDictionary *locationPDic = @{
                                   @"name":_provinceEntity.name,
                                   @"id"  :_provinceEntity.cityID
                                   };
    NSDictionary *loactionCDic = @{
                                   @"name":_cityEntity.name,
                                   @"id"  :_cityEntity.cityID
                                   };
    NSDictionary *locationDic  = @{
                                   @"province":locationPDic,
                                   @"city":loactionCDic
                                   };
    NSMutableArray *fileParameter = [[NSMutableArray alloc] init];
    for(NSDictionary *fileInfo in allFileArr)
    {
        NSDictionary *fileParameterInfo = @{
                                            @"fileName":fileInfo[@"name"],
                                            @"fileId"  :fileInfo[@"fileId"]
                                            };
        [fileParameter addObject:fileParameterInfo];
    }
    
    NSMutableArray *lawParameter = [[NSMutableArray alloc] init];
    for(NSDictionary *lawInfo in allLawerArr)
    {
        [lawParameter addObject:lawInfo[@"_id"]];
    }
//    NSDictionary *parameterID = @{
//                                @"uid":[[UserInfoDetail sharedInstance] getUserID],
//                                };
    NSDictionary *parameterData = @{
                                    @"amount":moneyString,
                                    @"location":locationDic,
                                    @"role":_currentRole,
                                    @"adviceFee":total,
                                    @"discount":discounted,
                                    @"costs":agencyCost,
                                    @"type":[currentCase objectForKey:@"categoryId"],
                                    @"files":fileParameter,
                                    @"intention":lawParameter
                                    };
    return @{
             @"uid":[[UserInfoDetail sharedInstance] getUserID],
             @"data":parameterData
             };
    
}

- (BOOL)isUserInputValidate
{
    BOOL validate = YES;
    if(![self isUserInputNum:moneyString])
    {
        [self showAlertWarnningView:@"提示" andContent:@"起诉金额不能为空并且必须为整数。"];
        validate = NO;
    }
    else if (_provinceEntity == nil)
    {
        [self showAlertWarnningView:@"提示" andContent:@"请选择完整的省、市。"];
        validate = NO;
    }
    else if (allFileArr.count==0||allFileArr.count>10)
    {
        [self showAlertWarnningView:@"提示" andContent:@"请上传相关文件。最多可上传10个文件。"];
        validate = NO;
    }
    else if (allLawerArr.count==0||allLawerArr.count>3)
    {
        [self showAlertWarnningView:@"提示" andContent:@"请选择意向代理律师，最多可选择三位意向律师。"];
        validate = NO;
    }
    for(NSDictionary *imageInfo in allFileArr)
    {
        NSString *statusStrings  = imageInfo[@"isUpload"];
        if(![statusStrings isEqualToString:@"YES"])
        {
            [self showAlertWarnningView:@"提示" andContent:@"还有没有上传的附件"];
            validate = NO;
            break;
        }
    }

    if(validate)
    {
        return YES;
    }
    else
    {
        return NO;
    }
}
@end
